package com.example.rpc_core.loadbalance.impl;

import com.example.rpc_core.loadbalance.LoadBalancer;
import com.example.rpc_core.model.ServiceInfo;

import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

public class RoundRobinLoadBalancer implements LoadBalancer {
    /**
     * 设置当前轮询的下标
     * @param requestParams
     * @param serviceInfoList
     * @return
     */
    private final AtomicInteger currentIndex = new AtomicInteger(0);
    @Override
    public ServiceInfo select(Map<String, Object> requestParams, List<ServiceInfo> serviceInfoList) {
        if (serviceInfoList.isEmpty())
        {
            return null;
        }
        int size = serviceInfoList.size();
        if (size==1){
            return serviceInfoList.get(0);
        }
        //取模算法轮询
        int i = currentIndex.getAndIncrement() % size;
        return serviceInfoList.get(i);
    }
}
